import shell from "shelljs";
import scpClient from "scp2";
import ora from "ora";
import fs from "fs";
import config from "./config.js";

// 打包 npm run build
const compileDist = async () => {
  if (shell.exec(`npm run build`).code === 0) {
    console.log('打包成功')
  }
}

// 连接远端服务器
async function connectSSh() {
  const server = {
    host:config.ip,//服务器IP
    port:config.port,//服务器端口
    username:config.username,//服务器ssh登录用户名
    password:config.password,//服务器ssh登录密码
    path:config.path//服务器web目录
  }
  const loading = ora('正在部署至 ' + config.ip);
  loading.start();
  // 开始部署至远端服务器
  scpClient.scp(config.localPath, server, (err)=>{
    loading.stop()
    if(err) {
      console.log('部署失败')
      console.error(err);
      throw err
    }else {
      console.log('部署成功')
    }
  })
}
function checkExistBuild() {
  return new Promise((resolve, reject) => {
    fs.stat(config.localPath, function(err, stats) {
      // 先判断文件(夹)是否存在
      if (!stats) {
        resolve(false);
      } else if (stats.isDirectory()) {
        resolve(true);
      } else {
        resolve(false);
      }
    })
  })
}

function deleteFolder(path) {
  let files = [];
  if( fs.existsSync(path) ) {
    files = fs.readdirSync(path);
    files.forEach(function(file,index){
      let curPath = path + "/" + file;
      if(fs.statSync(curPath).isDirectory()) {
        deleteFolder(curPath);
      } else {
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}
// 定义主任务
async function runTask () {
  // 需要重新打包, 如果已经存在包则先删除 -- 此处可省略
  let bool = await checkExistBuild();
  if (bool) {
    const loading = ora('正在删除文件夹: ' + config.localPath);
    loading.start();
    deleteFolder(config.localPath);
    loading.stop();
  }
  await compileDist() // 打包完成
  await connectSSh() // 提交上传
}

// 开始执行
runTask()
